/**
 * /**
 * 给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
 * <p>
 * 如果数组中不存在目标值 target，返回 [-1, -1]。
 * <p>
 * 你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * <p>
 * 输入：nums = [5,7,7,8,8,10], target = 8
 * 输出：[3,4]
 * <p>
 * 示例 2：
 * <p>
 * <p>
 * 输入：nums = [5,7,7,8,8,10], target = 6
 * 输出：[-1,-1]
 * <p>
 * 示例 3：
 * <p>
 * <p>
 * 输入：nums = [], target = 0
 * 输出：[-1,-1]
 * <p>
 * <p>
 * <p>
 * 提示：
 * <p>
 * <p>
 * 0 <= nums.length <= 10⁵
 * -10⁹ <= nums[i] <= 10⁹
 * nums 是一个非递减数组
 * -10⁹ <= target <= 10⁹
 * <p>
 * <p>
 * Related Topics 数组 二分查找 👍 1967 👎 0
 */


package com.xixi.basicAlgroithms.binarySearch;

public class ID00034FindFirstAndLastPositionOfElementInSortedArray {
    public static void main(String[] args) {
        Solution solution = new ID00034FindFirstAndLastPositionOfElementInSortedArray().new Solution();
    }


    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] searchRange(int[] nums, int target) {


            int left = 0;
            int right = nums.length;


            //left side
            while (left < right) {//end when left == right
                int mid = left + (right - left) / 2;
                if (nums[mid] == target) {
                    right = mid; //keep move to left
                } else if (nums[mid] < target) {
                    left = mid + 1;
                } else if (nums[mid] > target) {
                    right = mid;
                }
            }

            int leftSide = -1;
            if (left != nums.length) {
                leftSide = nums[left] == target ? left : -1;
            }


            //right side
            left = 0;
            right = nums.length;
            while (left < right) {//end when left == right
                int mid = left + (right - left) / 2;
                if (nums[mid] == target) {
                    left = mid + 1; //keep move to right
                } else if (nums[mid] < target) {
                    left = mid + 1;
                } else if (nums[mid] > target) {
                    right = mid;
                }
            }

            int rightSide = -1;
            if (right != 0) {
                rightSide = nums[right - 1] == target ? right - 1 : -1;
            }

            return new int[]{leftSide, rightSide};


        }
    }
//leetcode submit region end(Prohibit modification and deletion)


}